from socket import *
import struct, binascii

from jt808log import log
import jt808protocol

import threading
from _redis import pub

pub_db = pub._pub()

LISTEN_ADDR = ('127.0.0.1', 12345)
client_Num = 5

#创建主socket类 返回一个绑定了ip、port的socket
class build_ServerSocket(object):

	def _build(self, serverAddr=('', 6444)):

		serverSocket = socket(AF_INET, SOCK_STREAM)
		serverAddr=LISTEN_ADDR
		serverSocket.bind(serverAddr)
		serverSocket.listen(client_Num)

		return serverSocket


#有链接就分配一个接收数据线程 循环等待下一个链接
def dispatch(serverSocket=None):

	while True:
		print('Server:%s Waiting!' % str(serverSocket.getsockname()))
		clientSocket,clientAddr = serverSocket.accept()
		print('Hello number: ', clientAddr[1])
		threading.Thread(target=read_data, args=(clientSocket,)).start()	#启动一个接收数据线程
	
	serverSocket.close()


# 接收数据
def read_data(clientSocket=None):
		
	# 数据库操作
	from webJt808.model import Truck_Base
	
	if clientSocket:
		while True:
			#socket 原始数据
			data = clientSocket.recv(1024)
			log.info('Socket_Raw: %s' % data)
			# print(binascii.hexlify(data))

			#将接收到的数据发布到 redis 的 cctv1
			# _channel = 'cctv1'
			# db = pub_db
			# pub_db.publish(_channel, data)

			# 解析接收到的jt808数据
			msg_ins = jt808protocol.Message.pasrseMsg(data)
			log.info(msg_ins)

			# 将解析后的数据保存到数据库
			if msg_ins:
				if msg_ins.commandId == 0x0200:
					vehicle_sim = msg_ins.termPhone
					lon = 0
					lat = 0
					gps_Time = msg_ins.Time
					systime = ''

					v_location = Truck_Base(vehicle_sim=vehicle_sim,lon=lon,lat=lat, gps_Time=gps_Time, systime=systime)

					log.info('Truck_Base:', str(v_location))

			

			# 返回数据 根据消息类中标记的 requirAck 
			if msg_ins:
				rst = []
				if True:
					rst = msg_ins.generateData()
				
				clientSocket.send(rst)
				log.info('resp_data: %s' % rst)

			if not data:
				#不再接收数据时 关闭socket
				clientSocket.close()
				break


if __name__ == '__main__':

	dispatch(build_ServerSocket()._build())

	# from webJt808.model import Truck_Base